import $http from '@/utils/request'
import * as $API from '@/utils/api'
import { zcJsonCompare, zcJsonWordCompare } from '@utils/tools'
import { getSession, setSession } from '@utils/navigation'
import { setLocal, getLocal } from '@/utils/navigation'

export default {
  state: {
    countryList: [], // 国家下拉菜单
    productList: [], // 产品下拉菜单
    cityList: [], // 城市下拉菜单
    dfareCountryList: [], // 司补国家
    dfareCityList: [], //司补城市
    dfareCityLoading: false, // 司补城市下拉读取状态
    indicatorSize: getLocal('indicatorSize'), // 指标监控 宽高设置
    cityLoading: false, // 正在读取城市列表
  },
  getters: {},
  mutations: {
    setCountryList(state, data) {
      state.countryList = data
      zcJsonWordCompare(state.countryList, 'country_name_en')
    },
    setCityList(state, data) {
      state.cityList = data
      zcJsonWordCompare(state.cityList, 'city_name_en')
    },
    setProductList(state, data) {
      state.productList = data
    },
    setDfareCountryList(state, data) {
      state.dfareCountryList = data
    },
    setDfareCityList(state, data) {
      state.dfareCityList = data
    },
    setIndicatorSize(state, data) {
      let indicatorSizePre = JSON.parse(state.indicatorSize)
      indicatorSizePre[data.label] = data.value
      setLocal('indicatorSize', JSON.stringify(indicatorSizePre))
    },
    setCityLoading(state, data) {
      state.cityLoading = data
    },
    setDfareCityLoading(state, data) {
      state.dfareCityLoading = data
    },
  },
  actions: {
    getSearchFormList({ commit }, data) {
      return new Promise((resolve) => {
        let getCountryList = $http.get($API.GET_ALL_COUNTRY)
        let getProductList = $http.get($API.LEGO_GET_PRODUCT)
        Promise.all([getCountryList, getProductList]).then((res) => {
          commit('setCountryList', res[0].data)
          commit('setProductList', res[1].data)
          resolve(res)
        })
      })
    },
    getCityList({ commit }, data) {
      return new Promise((resolve) => {
        commit('setCityLoading', true)
        $http
          .get($API.GET_CITY, { country_code: data })
          .then((res) => {
            if (res.errno === 0 && res.data) {
              commit('setCityList', res.data)
              resolve('success')
            }
          })
          .finally(() => {
            commit('setCityLoading', false)
          })
      })
    },
    getDfareCountryList({ commit }, data) {
      $http.get($API.DFARE_GET_COUNTRY).then((res) => {
        commit('setDfareCountryList', res.data)
      })
    },
    getDfareCityList({ commit }, data) {
      commit('setDfareCityLoading', true)
      $http
        .get($API.DFARE_GET_CITY, {
          country_code: data[0],
          creation_source: data[1],
        })
        .then((res) => {
          commit('setDfareCityList', res.data)
        })
        .finally(() => {
          commit('setDfareCityLoading', false)
        })
    },
  },
}
